<?php
namespace app\admin\controller;

use app\admin\model\Admin;
use think\Request;
use think\captcha\Captcha;
use think\Session;

class Login extends Common
{
    public function index()
    {
        return $this->fetch();
    }

    public function dologin(Request $request)
    {
        $user_name = $request->post('username', '', 'filterString');
        $password = $request->post('password');
        $validate_code = $request->post('code', '', 'filterString');
        if (!$user_name) {
            $this->error('请输入用户名');
        } elseif (!$password) {
            $this->error('请输入密码');
        }
        $captcha = new Captcha();
        if (!$captcha->check($validate_code)) {
            $this->error('验证码错误');
        }

        $adminModel = new Admin();
        $user_info = $adminModel->getInfoByField('user_name', $user_name);
        if (!$user_info || $user_info->password != md5($password)) {
            $this->error('用户名或密码错误');
        } elseif ($user_info->status == 2){
            $this->error('用户账号已被冻结');
        }
        $adminModel->upTimeIp($user_info->id);
        Session::set('user_name', $user_info->user_name);
        Session::set('user_id', $user_info->id);
        $this->success('登录成功', '/admin/index');
    }

    //验证码
    public function validataCode()
    {
        $config =    [
            // 验证码位数
            'length'      =>    4,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
    //退出登录
    public function loginout()
    {
        session('user_name', null);
        session('user_id', null);
        $this->success('退出成功', '/admin/login');
    }

}
